package test.LeetCode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Projectname: algorithm-training-camp
 * @Filename: Solution1
 * @Author: FANSEA
 * @Date:2024/10/30 15:02
 */
public class Solution1 {
    // 56.合并区间 https://leetcode.cn/problems/merge-intervals/
    public int[][] merge(int[][] intervals) {
        if (intervals.length == 0) {
            return new int[0][2];
        }
        int l = intervals.length;
        Arrays.sort(intervals, (a, b) -> a[0] - b[0]);
        List<int[]> list = new ArrayList<>();
        int start = intervals[0][0];
        int end = intervals[0][1];
        for (int i = 1; i < l; i++) {
            if (end >= intervals[i][0]) {
                end = Math.max(end,intervals[i][1]);
            }
            else if(end < intervals[i][0]){
                list.add(new int[]{start,end});
                start = intervals[i][0];
                end = intervals[i][1];
            }
            if (i==l-1){
                list.add(new int[]{start,end});
            }
        }
        int[][] res = new int[list.size()][2];
        for (int[] ints : list){
            res[list.indexOf(ints)] = ints;
        }
        return res;
    }

    public static void main(String[] args) {
        Solution1 solution1 = new Solution1();
        int[][] intervals = {{1,4},{4,5}};
        int[][] merge = solution1.merge(intervals);
        for (int[] ints : merge)
            System.out.println(Arrays.toString(ints));
    }


}
